from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.views import logout
from staff.models import *
from datetime import datetime

def redirect(request, texto):
    return HttpResponseRedirect('/')

def index(request):
    return render_to_response('index/home.html', {'request': request})

def start_session(request):
    try:
        next = request.GET['next']
    except:
        next = '/'
    return render_to_response('index/login.html', {'request': request, 'next': next, 'styles':['login.css'], 'scripts': ['login.js']})

def join(request):
    u = request.POST['user']
    p = request.POST['password']
    next = request.POST['next']
    usr = authenticate(username=u, password=p)
    if usr is not None:
        if usr.is_active:
            login(request, usr)
            persn = Person.objects.get(user=usr)
            vendor = Vendor.objects.get(person_ptr=persn)
            request.session['vendor'] = vendor
            log = Log(id_user=usr, action=2, id_action=0, datetime=datetime.now())
            log.save()
        else:
            return render_to_response('index/error.html', {'request': request, 'error': 'The user has been disabled.', 'styles': ['error.css'], 'scripts': ['error.js']})
    else:
        return render_to_response('index/error.html', {'request': request, 'error': 'Username or password wrong', 'styles': ['error.css'], 'scripts': ['error.js']})
    return HttpResponseRedirect(next)

def close_session(request):
    log = Log(id_user=request.user, action=3, id_action=0, datetime=datetime.now())
    log.save()
    try:
        del request.session['vendor']
    except:
        pass
    logout(request)
    return redirect(request, '')

def building(request):
    return render_to_response('index/building.html', {'request': request})
